#!/usr/bin/env python
#
# Copyright 2008 Richard J. Bell. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

""" Main application file for great-loop site.

great-loop.py implements a Google app engine web site to support users
interested in America's Great Loop.  It is a personal project supporting my 
interest in doing the Great Loop and to experiment with several Google 
technologies including:
  - todo

The site provides:
  - A wiki to hold reference information about the Great Loop
  - Wiki entries may have geo locations
  - Entries with geo locations can be displayed on a google map
  - All entries are viewable in a list format
  - Wiki entries have comments
  - Anyone can view the entire site
  - Users can register.  
  - Registered users can add and edit wiki pages
  - Provisions for displaying NOAA raster and enc charts as a google map mashup
"""

__version__ = '$Revision 0.1$'
__author__  = "Richard Bell <rbell01824@earthlink.net>"
__date__ = 'Dec 12, 2008'
__credits__ = """
Various portions of this code and site are derived from open sources including:
  todo
  """
#===============================================================================
# 
# MODS:
#     20081204 - Initial creation rjb
#
#===============================================================================

#===============================================================================
# Work in progress code start
#===============================================================================
#Parameters:
#  url: opt, string, The URL to leave the Yamie at.
#  timeout: opt, float, Seconds to wait before timeout.  Default self.timeout.
#  noEventsTimeout: opt, float, Seconds for no events.  Default self.noEventsTimeout.
#Returns: The new Yamie with LocationURL == URL

#Usage:
#>>> import Yamie
#>>> ie = Yamie.NewYamie('www.google.com')
#>>> ie.LocationURL
#u'http://www.google.com/'
#>>> ie.Y_Quit()
#True
#===============================================================================
# Work in progress code end
#===============================================================================

import os
from google.appengine.ext.webapp import template

import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

#===============================================================================
# DBs
#===============================================================================

#-------------------------------------------------------------------------------
# user preferances for the current user
#-------------------------------------------------------------------------------
class UserPrefs(db.Model):
  user = db.UserProperty()
  # fixme - rest of user preferences go here
  
#-------------------------------------------------------------------------------
# references
#-------------------------------------------------------------------------------
class References(db.Model):
  title = db.StringProperty(required=True, multiline=False)   # 
  novel = db.StringProperty(multiline=True)                   #
  user = db.UserProperty()                                    # user who created
  # fixme - rest of user preferences go here

#-------------------------------------------------------------------------------
# tbd
# user = users.get_current_user()
# if user:
#  q = db.GqlQuery("SELECT * FROM UserPrefs WHERE user = :1", user)
#  userprefs = q.get()
#-------------------------------------------------------------------------------
  
class Greeting(db.Model):
  author = db.UserProperty()
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)

#===============================================================================
# Methodes
#===============================================================================
#-------------------------------------------------------------------------------
# Handles /
#-------------------------------------------------------------------------------
class MainPage(webapp.RequestHandler):
  """ Support main page processing.
  """ 
  def get(self):
    """ Handle the get request for /.
    Parameters: None
    Returns: None
    Usage: None
    """
    greetings_query = Greeting.all().order('-date')
    greetings = greetings_query.fetch(10)

    # if we know the user, return them to their last page with a redirect
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
      # fix me: here return the user to there last page with a redirect
    # otherwise display the main page
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'greetings': greetings,
      'url': url,
      'url_linktext': url_linktext,
      }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class Guestbook(webapp.RequestHandler):
  def post(self):
    greeting = Greeting()

    if users.get_current_user():
      greeting.author = users.get_current_user()

    greeting.content = self.request.get('content')
    greeting.put()
    self.redirect('/')

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/sign', Guestbook)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()